import requests
from pydispatch import dispatcher
from requests.auth import HTTPDigestAuth
import json
import time
import threading

from logger import log
from settings import settings


# 处理每个摄像头的数据
def poll_camera(camera):
    url_template = "http://{ip}/ISAPI/Thermal/channels/2/thermometry/1/rulesTemperatureInfo?format=json"
    url = url_template.format(ip=camera['ip'])
    auth = HTTPDigestAuth(camera['username'], camera['password'])

    while True:
        try:
            response = requests.get(url, auth=auth, timeout=10)
            response.raise_for_status()  # 检查请求是否成功

            data = response.json()
            # 提取maxTemperature
            therm_info = data.get("ThermometryRulesTemperatureInfoList", {}).get("ThermometryRulesTemperatureInfo", [])
            if therm_info:
                max_temp = therm_info[0].get("maxTemperature")
                dispatcher.send("temperature", camera_name=camera['name'], location=camera['location'], temperature=max_temp)
                log.info(f"摄像头 {camera['name']} ({camera['ip']}): 最大温度 = {max_temp}°C")
            else:
                log.info(f"摄像头 {camera['name']} ({camera['ip']}): 无温度数据")

        except requests.exceptions.RequestException as e:
            log.info(f"摄像头 {camera['name']} ({camera['ip']}) 访问失败: {e}")
            time.sleep(30)
        except json.JSONDecodeError:
            log.info(f"摄像头 {camera['name']} ({camera['ip']}) 返回的不是有效的JSON")
        except Exception as e:
            log.info(f"摄像头 {camera['name']} ({camera['ip']}) 发生错误: {e}")

        time.sleep(5)  # 轮询间隔5秒


def main():
    cameras = settings.temperatureList

    threads = []
    for camera in cameras:
        t = threading.Thread(target=poll_camera, args=(camera,))
        t.daemon = True  # 设置为守护线程，主线程结束时自动退出
        t.start()
        threads.append(t)

    try:
        while True:
            time.sleep(1)  # 主线程保持运行
    except KeyboardInterrupt:
        log.info("程序已终止。")


if __name__ == "__main__":
    main()
